package com.backend.service.impl;

import com.backend.common.ErrorCode;
import com.backend.common.PageRequest;
import com.backend.common.PageResponse;
import com.backend.exception.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.backend.entity.User;
import com.backend.service.UserService;
import com.backend.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;

import static com.backend.constant.UserConstant.USER_LOGIN_STATE;

/**
 *
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{


    /**
     * 登录
     *
     * @param userName 用户名
     * @param userPassword 密码
     * @param request 可以存储session（user_login键对值）
     * @return 新用户
     */
    @Override
    public User userLogin(String userName, String userPassword, HttpServletRequest request) {

        if (StringUtils.isAnyBlank(userName, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "登录时，参数为空");
        }

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName, userName).eq(User::getUserPassword, userPassword);
        User user = this.getOne(lambdaQueryWrapper);
        if (user == null) {
            log.info("Unable to find user during login");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或账号密码错误");
        }
        // 前端的session中就保存了user_login的属性值，通过这个参数，我们就可以确定用户是否在登录状态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return user;
    }

    /**
     * 注册
     *
     * @param userName 用户名
     * @param userPassword 密码
     * @return -1为插入失败，否则返回新用户ID
     */
    @Override
    public long userRegister(String userName, String userPassword) {
        // 参数为空
        if (StringUtils.isAnyBlank(userName, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "注册时，参数为空");
        }
        // 查询
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName, userName).eq(User::getUserPassword, userPassword);
        long count = this.count(lambdaQueryWrapper);

        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "注册时，账号重复");
        }

        User user = new User();
        user.setUserName(userName);
        user.setUserPassword(userPassword);

        boolean saveResult = this.save(user);
        if (!saveResult) {
            log.info("User insertion failed during registration");
            return -1;
        }
        return user.getId();
    }

    /**
     * 退出登录
     *
     * @param request 删除user_login键对值
     * @return
     */
    @Override
    public Boolean userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public User getSession(HttpServletRequest request) {
        return null;
    }

    @Override
    public Boolean resetPassword(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(User::getUserName, user.getUserName());
        int count = this.count(lambdaQueryWrapper);
        if (count > 0) {
            user.setUserPassword("123456");
            return true;
        } else {
            return false;
        }
    }

    @Override
    public PageResponse page(PageRequest pageRequest) {
        Page<User> page = new Page<>(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        HashMap<String, Object> params = pageRequest.getParams();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (params.size() > 0) {
            for (String key: params.keySet()) {
                if (StringUtils.isNotBlank(params.get(key).toString()))
                    queryWrapper.eq(key, params.get(key));
            }
        }
        this.page(page, queryWrapper);
        return new PageResponse(page);
    }
}







